#include "mystdio.h"


MYFILE* myfopen(const char* filepath, const char* mode)
{
    MYFILE* fp = (MYFILE*)malloc(sizeof(MYFILE));
    if(fp == NULL)
        return fp;
    if(strcmp(mode, "w") == 0)
    {
        //写方式
        fp->fileno = open(filepath, O_WRONLY|O_CREAT|O_TRUNC, 0666); 
    }
    else if(strcmp(mode, "r") == 0)
    {
        //读方式
        fp->fileno = open(filepath, O_RDONLY); 
    }
    else if(strcmp(mode, "a") == 0)
    {
        //追加方式
        fp->fileno = open(filepath, O_WRONLY|O_CREAT|O_APPEND, 0666); 
    }
    else
    {
        //错误
        free(fp);
        fp = NULL;
        return fp;
    }
    fp->pos = 0;
    fp->flushtype = LINEFLUSH; //默认是行刷新，可以根据要求自定义修改
    return fp;
}

void myfclose(MYFILE* fp)
{
    myfflush(fp);
    close(fp->fileno);
    free(fp);
    fp = NULL;
}

int myfread(void* bf, size_t size, size_t n, MYFILE* fp)
{
    if(fp == NULL) return 0;
    int ret = read(fp->fileno, bf, size * n);
    return ret;
}


int myfwrite(const void* bf, size_t size, size_t n, MYFILE* fp)
{
    if(fp == NULL) return 0;
    memcpy(fp->buf+fp->pos, bf, size*n);
    int len = strlen(bf);
    fp->pos += len;
    if(fp->flushtype == LINEFLUSH && fp->buf[fp->pos-1] == '\n')
    {
        int ret = write(fp->fileno, bf, size * n);
        fp->pos = 0;
        return ret;
    }
    return len;
}

void myfflush(MYFILE* fp)
{
    write(fp->fileno, fp->buf, strlen(fp->buf));
}
